import urllib.request
import urllib.parse
import json
import datetime
import socket
import winsound


def workspace(iphone: str, tag: str):
    s = "浙江 杭州 西湖区"
    s=urllib.parse.quote(s)
    url = "https://www.apple.com.cn/shop/pickup-message-recommendations?mt=compact&location=%s&product="%s + iphone
    timeout = 3
    duration = 1000  # millisecond
    freq = 440  # Hz
    while(True):
        try:
            socket.setdefaulttimeout(timeout)
            req = urllib.request.Request(url)
            response = urllib.request.urlopen(req).read().decode("utf-8")
            res_dic = json.loads(response)
            info = res_dic["body"]["PickupMessage"]["stores"][0]["partsAvailability"]
            print(str(datetime.datetime.now()) + " : 扫描正在执行中。。。")
            for i in info:
                if i == tag:
                    winsound.Beep(freq, duration)
                    print("快抢呀！")
                    break
        except:
            print("上一次执行超时，重新执行")
            continue


if __name__ == '__main__':
    """
    MU2P3CH/A   iPhone 15 Pro Max 256GB 白色
    MU2Q3CH/A   iPhone 15 Pro Max 256GB 原色
    """
    workspace("MU2Q3CH/A", "MU2P3CH/A")